<template>
  <el-form :inline="inline" ref="formEl" size="small" label-position="right"  class="demo-form-inline" :model="formModel" :rules="formRules">
    <form-item v-for="(item, index) in state.formSchema" :key="item" :formSchema="item" :formModel="formModel"></form-item>
    <el-form-item v-for="action in state.formActions" :key="action">
      <el-button type="primary" size="small" :icon="action.icon" @click="handleOperateAction(formEl,action.type)">{{ action.label }}</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import { FormActionsType, FormDataRowType, FormDataType } from 'types/form'
import { FormInstance, FormRules } from 'element-plus';
import { watch,ref } from 'vue';
import { objTKV } from '@/utils/_';

interface FormSchemaType {
  schema: any,
  actions: any,
  inline: boolean,
  [key: string]: unknown | any
}

const emits = defineEmits(['handleOperateAction','update:modelValue'])

const props = defineProps<FormSchemaType>()

const formEl = ref<FormInstance>()

let state = reactive({
  formSchema: props.schema,
  formActions: props.actions,
})



let formModel = ref<FormDataType>()
const formRules: FormRules = reactive({})

/**
 * @description: 初始化Form默认值
 * @return {*}
 */
const initFormModel = () => {
  formModel.value = objTKV(props.schema,'field')
}

/**
 * @description: 初始化From校验规则
 */
const initFormRules = () => {
  state.formData?.forEach((e:any) => {
    (e.rule && e.field) ? formRules[e.field] = e.rule : ''
  })
}




watch(formModel,(n,o) => {
    
  emits('update:modelValue',n)
},{deep: true})

// 初始化Form
onBeforeMount(() => {
  initFormModel()
  initFormRules()
})

const searchForm = async (formEl: FormInstance | undefined) => {
  
  
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      emits('handleOperateAction',{data:formModel,action: 'search'})
    } else {
      
    }
  })
}
const submitForm = async (formEl: FormInstance | undefined) => {
  
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      emits('handleOperateAction',{data:formModel,action: 'submit'})
    } else {
      
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emits('handleOperateAction',{action: 'reset'})
}


const handleOperateAction = (formEl: FormInstance | undefined,type:FormActionsType) => {
  switch (type) {
    case 'submit':
      submitForm(formEl)
      break;
    case 'reset':
      resetForm(formEl)
      break;
    case 'search':
      searchForm(formEl)
      break;
    default:
      break;
  }
}

defineExpose({formEl})

</script>

<style lang="scss" scoped></style>
